/**
 * @author 雷明浩
 * @date 2025/6/3 14:29
 */
public class SortInList {
    // newcoder 单链表的排序
    // https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

    /**
     * 时间复杂度 O(n^2)
     * @param head
     * @return
     */
    public ListNode sortInList1 (ListNode head) {
        // write code here
        ListNode phead = new ListNode(-1);
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            if (phead.next == null || cur.val < phead.next.val) {
                cur.next = phead.next;
                phead.next = cur;
            }else {
                ListNode cur1 = phead.next.next;
                ListNode prev = phead.next;
                while (cur1 != null && cur1.val <= cur.val) {
                    prev = cur1;
                    cur1 = cur1.next;
                }
                cur.next = cur1;
                prev.next = cur;
            }
            cur = curNext;
        }
        return phead.next;
    }

    /**
     * 归并排序，时间复杂度 O(nlogn)
     * @param head
     * @return
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            if (fast == null) {
                break;
            }
            slow = slow.next;
        }
        ListNode nextList = slow.next;
        slow.next = null;
        ListNode leftList = sortInList(head);
        ListNode rightList = sortInList(nextList);
        return merge(leftList, rightList);
    }

    private ListNode merge(ListNode head1, ListNode head2) {
        ListNode phead = new ListNode(-1);
        ListNode cur = phead;
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null && cur2 != null) {
            if (cur1.val <cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (cur1 != null) {
            cur.next = cur1;
        }
        if (cur2 != null) {
            cur.next = cur2;
        }
        return phead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(3);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        SortInList sortInList = new SortInList();
        ListNode result = sortInList.sortInList(head);
    }
}